<template>
  <view>
    <view class="goods-detail" :style="{height: (windowHeight - 44 - 50) + 'px'}">
      <!--轮播图-->
      <view class="thumb-covers">
        <swiper circular :indicator-dots="true" :autoplay="true" :interval="2000"
                :duration="500">
          <swiper-item v-for="(cover, coverIdx) in state.detail.covers" :key="coverIdx">
            <image :src="cover" style="width: 100%; height: 150px;" mode="scaleToFill"></image>
          </swiper-item>
        </swiper>
      </view>
      <!--价格、收藏-->
      <view class="sale-price">
        <view class="price">
          <text class="symbol">￥</text>
          <text class="front">{{ slicePrice(state.detail.price, true) }}</text>
          <text class="back">.{{ slicePrice(state.detail.price, false) }}</text>
        </view>
        <view class="collect">
          <uni-fav bgColorChecked="#e43d33" :checked="state.favChecked" @click="favClick"/>
        </view>
      </view>
      <!--销售标题、子标题-->
      <view class="sale-title">
        <text class="title">{{ state.detail.title }}</text>
        <text class="summary">{{ state.detail.summary }}</text>
      </view>
      <!--选择规格-->
      <view class="spec">
        <view class="spec-selected" @tap="showSpec">
          <text class="label">已选</text>
          <text>{{ state.auxiliary.skuSelectedData.selectedProduct.spec }}</text>
        </view>
        <vk-data-goods-sku-popup
            ref="skuPopup"
            v-model="state.auxiliary.skuComponentConf.skuKey"
            border-radius="20"
            :z-index="990"
            :localdata="state.auxiliary.skuComponentConf.goodsInfo"
            :mode="state.auxiliary.skuComponentConf.skuMode"
            @open="onOpenSkuPopup"
            @close="onCloseSkuPopup"
            @add-cart="addCart"
            @buy-now="buyNow"
        ></vk-data-goods-sku-popup>
      </view>
      <!--选择收货地址-->
      <view class="address" @tap="showAddressList">
        <text class="label">送至</text>
        <text class="address-selected">{{ state.auxiliary.skuSelectedData.selectedAddrStr }}</text>
      </view>
      <!--评价-->
      <ReviewComp :review="state.review"/>
      <!--品牌信息-->
      <view class="brand" v-if="state.detail.brand">
        <view class="logo">
          <image :src="state.detail.brand.logo" style="width: 100px; height: 100px;"></image>
        </view>
        <view class="info">
          <text class="name">{{ state.detail.brand.name }}</text>
          <text class="slogan">{{ state.detail.brand.slogan }}</text>
        </view>
      </view>
      <!--规格信息-->
      <view class="intro">
        <uni-collapse>
          <uni-collapse-item title="规格参数">
            <view class="list">
              <view class="item" v-for="(spuItem, spuIdx) in state.detail.spu" :key="spuIdx">
                <text class="label">{{ spuItem.name }}</text>
                <text class="value">{{ spuItem.value }}</text>
              </view>
            </view>
          </uni-collapse-item>
          <!--商详图片-->
          <uni-collapse-item title="商品详情" :open="true">
            <view class="gallery">
              <image class="item" :src="img" v-for="(img, imgIdx) in state.detail.pictures" :key="imgIdx"></image>
            </view>
          </uni-collapse-item>
        </uni-collapse>
      </view>
    </view>
    <uni-goods-nav :fill="true" :options="state.auxiliary.skuNavConf.options"
                   :button-group="state.auxiliary.skuNavConf.buttonGroup" @click="handleGoodsNavClick"
                   @buttonClick="goodsNavClick"/>
    <uni-popup ref="popupRef" background-color="#fff" type="bottom" @change="popupChange">
      <view class="popup-content">
        <AddressPanel :address-list="state.addressList" @return-addr-event="handleReceiveAddr"/>
      </view>
    </uni-popup>
  </view>
</template>
<script setup lang="ts">
import {onLoad} from "@dcloudio/uni-app";
import {ref} from "vue";
import AddressPanel from "@/components/address/AddressPanel.vue";
import {assembleAddress, slicePrice} from "@/utils/str";
import type {AddressItemType, AddressLabelType} from "@/types/user";
import type {IReviewStat, ProductDetailType} from "@/types/product";
import ReviewComp from './components/review.vue'
import {ReviewCls} from "@/types/productcls";
import {
  collectProduct,
  getProductDetailData,
  getProductInfoData,
  getReviewsSummaryData,
  getReviewsTopData,
  isCollectedProduct,
  removeCollectProduct
} from "@/services/product";
import {getAddressListData} from "@/services/address";
import {addToShopCar, getShopCarStat} from "@/services/shopcar";

const {windowHeight} = uni.getSystemInfoSync()

const state = ref({
  params: {} as any, // 页面请求参数
  detail: {} as ProductDetailType, // 商详数据
  review: new ReviewCls({} as IReviewStat, []), // 评论数据
  addressList: [] as Array<AddressItemType>, // 收货地址
  addressLabelList: [] as AddressLabelType[], // 收货地址标签
  // 是否收藏
  favChecked: false as boolean,
  auxiliary: {
    // sku弹窗组件的配置
    skuComponentConf: {
      // 是否打开SKU弹窗
      skuKey: false,
      // SKU弹窗模式
      skuMode: 1,
      // 后端返回的商品信息
      goodsInfo: {} as any,
    },
    // sku导航组件的配置
    skuNavConf: {
      options: [
        {
          icon: 'cart',
          text: '购物车',
          info: 0
        }],
      buttonGroup: [
        {
          text: '加入购物车',
          backgroundColor: 'linear-gradient(90deg, #FFCD1E, #FF8A18)',
          color: '#fff'
        },
        {
          text: '立即购买',
          backgroundColor: 'linear-gradient(90deg, #FE6035, #EF1224)',
          color: '#fff'
        }
      ],
    },
    skuSelectedData: {
      // 已选择的收货地址
      selectedAddrStr: "请选择",
      // 已选择的商品信息
      selectedProduct: {
        spec: "请选择",
        skuId: 0,
        count: 1, // 选择的商品数量
      },
    }
  },
})
const popupRef = ref()
/**
 * 收藏
 */
const favClick = () => {
  if (state.value.favChecked) {
    // 取消收藏
    removeCollectProduct(state.value.params.id).then(() => {
      state.value.favChecked = !state.value.favChecked
      uni.showToast({
        title: "取消收藏成功",
        icon: "none"
      })
    }).catch(() => {})
  } else {
    // 加入收藏
    collectProduct(state.value.params.id).then(() => {
      state.value.favChecked = !state.value.favChecked
      uni.showToast({
        title: "收藏成功",
        icon: "none"
      })
    }).catch(() => {})
  }
}
/**
 * 打开sku弹窗
 */
const openSkuPopup = () => {
  /**
   * 获取商品信息
   * 这里可以看到每次打开SKU都会去重新请求商品信息,为的是每次打开SKU组件可以实时看到剩余库存
   */
  getGoodsSpecData(1)
  state.value.auxiliary.skuComponentConf.skuKey = true;
}
/**
 * 监听sku弹窗打开事件
 */
const onOpenSkuPopup = () => {
  console.log("监听 - 打开sku组件");
}
/**
 * 监听sku弹窗关闭事件
 */
const onCloseSkuPopup = () => {
  console.log("监听 - 关闭sku组件");
}
/**
 * 确认规格并提交事件
 * @param selectShop
 */
// 提交选择的规格前的动作
const beforeConfirmSpec = (selectShop: any) => {
  // 获取选择的规格
  state.value.auxiliary.skuSelectedData.selectedProduct.spec = selectShop.sku_name_arr.join(" ")
  state.value.auxiliary.skuSelectedData.selectedProduct.skuId = selectShop._id
  state.value.auxiliary.skuSelectedData.selectedProduct.count = selectShop.buy_num
  // 关闭弹窗
  state.value.auxiliary.skuComponentConf.skuKey = false
  console.log("@sku pop component, ", state.value.auxiliary.skuComponentConf.goodsInfo, selectShop)
}
/**
 * sku组件的加入购物车
 * @param selectShop
 */
const addCart = (selectShop: any) => {
  console.log("监听 - 加入购物车");
  beforeConfirmSpec(selectShop)
  addToShopCar(state.value.auxiliary.skuSelectedData.selectedProduct.skuId, 1).then((r) => {
    if (r.code === 0) {
      uni.showToast({
        title: "成功加入购物车",
        icon: "none"
      })
    } else {
      uni.showToast({
        title: r.msg,
        icon: "none"
      })
    }
  })
}
/**
 * sku组件的立即购买
 * @param selectShop
 */
const buyNow = (selectShop: any) => {
  console.log("监听 - 立即购买", selectShop);
  beforeConfirmSpec(selectShop)
}
/**
 * 唤出sku弹窗
 */
const showSpec = () => {
  openSkuPopup()
}

/**
 * 点击购物导航组件
 * @param e
 */
const goodsNavClick = (e: any) => {
  console.log("button click ", e)
  if (e.index === 0) {
    // 加入购物车逻辑
    if (state.value.auxiliary.skuSelectedData.selectedProduct.skuId) {
      addToShopCar(state.value.auxiliary.skuSelectedData.selectedProduct.skuId, 1).then((r) => {
        if (r.code === 0) {
          uni.showToast({
            title: "成功加入购物车",
            icon: "none"
          })
        } else {
          uni.showToast({
            title: r.msg,
            icon: "none"
          })
        }
      })
      return
    }
    openSkuPopup()
    return
  }
  if (e.index === 1) {
    // 立即购买逻辑
    if (state.value.auxiliary.skuSelectedData.selectedProduct.skuId) {
      uni.showToast({
        title: "已选择商品规格，直接进入结算页",
        icon: "none"
      })
      return
    }
    openSkuPopup()
    return;
  }
  uni.showToast({
    title: "未知的操作",
    icon: "none"
  })
}

/**
 * 处理购物导航组件的点击事件
 * @param e
 */
const handleGoodsNavClick = (e: any) => {
  if (e.index === 0) {
    // 导航到购物车
    uni.switchTab({
      url: "/pages/cart/cart"
    })
    return
  }
  console.log("goods nav onClick: ", e)
  uni.showToast({
    title: `点击${e.content.text}`,
    icon: 'none'
  })
}
/**
 * 弹窗变化事件
 * @param e
 */
const popupChange = (e: any) => {
  console.log("popup change: ", e)
}
/**
 * 弹出选择收货地址的弹窗
 */
const showAddressList = () => {
  popupRef.value.open()
}
/**
 * 接收收货地址列表组件选中的地址数据
 * @param id
 */
const handleReceiveAddr = (id: string) => {
  console.log("@goodsVue selected addr id is ", id)
  // 匹配对应的具体地址
  for (let i = 0; i < state.value.addressList.length; i++) {
    if (state.value.addressList[i].id === parseInt(id)) {
      state.value.auxiliary.skuSelectedData.selectedAddrStr = assembleAddress(state.value.addressList[i])
      break
    }
  }
  // 关闭弹出层
  popupRef.value.close()
}
/**
 * 获取商详
 * @param skuId
 */
const getGoodsDetailData = async (skuId: number) => {
  console.log("Get goods detail skuId:", skuId)
  await getProductDetailData(skuId).then((r) => {
    if (r.code === 0) {
      state.value.detail = r.data
    } else {
      uni.showToast({
        title: r.msg,
        icon: "none"
      })
    }
  }).catch(() => {})
}
/**
 * 获取商品的规格数据
 * @param skuId
 */
const getGoodsSpecData = async (skuId: number) => {
  console.log("Get goods spec productId: ", skuId)
  await getProductInfoData(skuId).then((r) => {
    if (r.code === 0) {
      state.value.auxiliary.skuComponentConf.goodsInfo = r.data
    } else {
      uni.showToast({
        title: r.msg,
        icon: "none"
      })
    }
  }).catch(() => {})
}
/**
 * 获取商品的评价
 * @param skuId
 */
const getGoodsReviewsStatData = async (skuId: number) => {
  console.log("Get goods review list productId: ", skuId)
  await getReviewsSummaryData(skuId).then((r) => {
    state.value.review.stat = r.data
  }).catch(() => {})
}
const getGoodsReviewTopData = async (skuId: number) => {
  await getReviewsTopData(skuId).then((r) => {
    state.value.review.list = r.data
  }).catch(() => {})
}
const getReviewData = async (skuId: number) => {
  await getGoodsReviewTopData(skuId)
  await getGoodsReviewsStatData(skuId)
}
/**
 * 获取用户的收货地址列表
 */
const getUserAddressListData = () => {
  console.log("Get user address list uid: 1")
  getAddressListData({page: 1, size: 10, orders: []}).then((r) => {
    state.value.addressList.push(...r.data.list)
  }).catch(() => {})
}
/**
 * 获取地址标签的数据
 */
const getAddressLabelListData = () => {
  state.value.addressLabelList = [
    {label: "家", value: "HOME"},
    {label: "公司", value: "WORK"},
  ] as AddressLabelType[]
}
const getShopCarStatData = async () => {
  await getShopCarStat().then((r) => {
    if (r.code === 0) {
      state.value.auxiliary.skuNavConf.options[0].info = r.data
    } else {
      uni.showToast({
        title: r.msg,
        icon: "none"
      })
    }
  })
}

const reqIsCollectedProduct = async (skuId: number) => {
  await isCollectedProduct(skuId).then((r) => {
    if (r.code === 0) {
      state.value.favChecked = r.data
    } else {
      uni.showToast({
        title: r.msg,
        icon: "none"
      })
    }
  })
}
onLoad((params: any) => {
  console.log("goods params: ", params)
  state.value.params = params
  console.log("@start req must data...")
  Promise.all([
    getGoodsSpecData(state.value.params.id),
    getGoodsDetailData(state.value.params.id),
    getReviewData(state.value.params.id),
    getShopCarStatData(),
    reqIsCollectedProduct(state.value.params.id)
  ])
  console.log("review data: ", state.value.review)
  getUserAddressListData()
  getAddressLabelListData()
})
</script>
<style lang="scss">
.goods-detail {
  overflow-x: auto;

  .sale-price {
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    padding: 10px 10px;

    .price {
      font-weight: bold;
      color: $uni-color-error;
      font-size: 22px;

      .back {
        font-size: 14px;
      }
    }

    .collect {
      display: flex;
      flex-direction: column;
      justify-content: space-between;
      font-size: 14px;
    }
  }

  .sale-title {
    background-color: #fff;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-bottom: 20px;
    padding: 10px 10px;

    .title {
      font-weight: bold;
      font-size: 16px;
      margin-bottom: 10px;
    }

    .summary {
      color: $uni-color-subtitle;
      font-size: 14px;
      color: $uni-color-error;
    }
  }

  .spec {
    background-color: #fff;
    padding: 10px 10px;

    .spec-selected {
      .label {
        margin-right: 20px;
      }
    }
  }

  .address {
    background-color: #fff;
    padding: 10px 10px;
    margin-bottom: 20px;

    .label {
      margin-right: 20px;
    }
  }

  .brand {
    background-color: #fff;
    display: flex;
    justify-content: flex-start;
    align-items: center;
    margin-bottom: 10px;
    padding-left: 10px;

    .logo {
      margin-right: 20px;
    }

    .info {
      display: flex;
      flex-direction: column;
      justify-content: space-between;

      .name {
        margin-bottom: 10px;
      }

      .slogan {
        color: $uni-color-subtitle;
        font-size: 14px;
      }
    }
  }

  .intro {
    .list {
      //padding: 10px 0;

      .item {
        display: flex;
        justify-content: space-around;
        border-bottom: 1px solid $uni-border-color;
        padding: 10px 0;

        .label {
          width: 30%;
          padding-right: 30px;
          border-right: 1px solid $uni-border-color;
          text-align: center;
        }

        .value {
          width: 70%;
          text-align: center;
        }
      }
    }

    .gallery {
      .item {
        display: block;
        width: 100%; /* 占据父元素的全部宽度 */
        min-height: 800px;
        max-height: 2000px;
      }
    }
  }
}

.uni-goods-nav {
  height: 50px;
  /* #ifndef APP-NVUE */
  display: flex;
  /* #endif */
  flex-direction: column;
  position: fixed;
  left: 0;
  right: 0;
  /* #ifdef H5 */
  left: var(--window-left);
  right: var(--window-right);
  /* #endif */
  bottom: 0;
}

.label {
  font-weight: bold;
  color: #000;
}

.image {
  height: 100%;
}

.popup-content {
  height: 350px;
}
</style>